#!/bin/bash

set -e

LEKTOR_APP_NAME=Lektor.app
SHELL_COMMAND_PATH=/usr/local/bin/lektor

# If LEKTOR_PATH isn't set, check /Applications and then ~/Applications for Lektor.app
if [ -x "/Applications/$LEKTOR_APP_NAME" ]; then
  LEKTOR_PATH="/Applications"
elif [ -x "$HOME/Applications/$LEKTOR_APP_NAME" ]; then
  LEKTOR_PATH="$HOME/Applications"
else
  # We havent found an Lektor.app, use spotlight to search for Lektor
  LEKTOR_PATH="$(mdfind "kMDItemCFBundleIdentifier == 'org.pocoo.lektor'" | head -1 | xargs -0 dirname)"

  # Exit if Lektor can't be found
  if [ ! -x "$LEKTOR_PATH/$LEKTOR_APP_NAME" ]; then
    echo "Cannot locate Lektor.app, it is usually located in /Applications."
    exit 1
  fi
fi

# Special commands for installing the proxy command globally.
if [ "$1" == "--install-shell-command" ]; then
  ln -fs "$LEKTOR_PATH/$LEKTOR_APP_NAME/Contents/Resources/local/bin/lektor-proxy" "$SHELL_COMMAND_PATH"
  echo 'Successfully installed the global lektor shell command'
  exit 0
elif [ "$1" == "--uninstall-shell-command" ]; then
  rm -f "$SHELL_COMMAND_PATH"
  echo 'Successfully uninstalled the global lektor shell command'
  exit 0
fi

exec "$LEKTOR_PATH/$LEKTOR_APP_NAME/Contents/Resources/lektor" "$@"
